/* eslint-disable */
import mRouter from '@/utils/router';
import mTabbar from '@/config/tabbar.js';
import {useUserStore} from '@/store/user.js';
//常用方法集合
export default {
	/**
	 * toast提示
	 */
	toast(title, duration = 3000, mask = false, icon = 'none') {
		if (Boolean(title) === false) {
			return;
		}
		uni.showToast({
			title,
			duration,
			mask,
			icon
		});
	},
	/**
	 * 开发环境全局打印日志
	 * @param {Object} title
	 */
	log(title) {
		if (process.env.NODE_ENV === 'development' && Boolean(title) === true) {
			console.log(JSON.stringify(title));
		}
	},
	/**
	 * 异步获取设备信息
	 */
	getInfoAsync() {
		return new Promise((resolve, reject) => {
			plus.device.getInfo({
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e.message);
				}
			});
		});
	},
	/**
	 * 安卓10不支持IMEI,则获取OAID
	 */
	getOaidAsync() {
		return new Promise((resolve, reject) => {
			plus.device.getOAID({
				success(e) {
					resolve(e);
				},
				fail(e) {
					reject(e.message);
				}
			});
		});
	},
	/**
	 * 获取一个随机数
	 * @param {Object} min
	 * @param {Object} max
	 */
	random(min, max) {
		switch (arguments.length) {
			case 1:
				return parseInt(Math.random() * min + 1, 10);
				break;
			case 2:
				return parseInt(Math.random() * (max - min + 1) + min, 10);
				break;
			default:
				return 0;
				break;
		}
	},
	/**
	 * 获取ios的IDFA
	 */
	getIdfa() {
		let idfa = '';
		try {
			if ('iOS' == plus.os.name) {
				let manager = plus.ios.invoke('ASIdentifierManager', 'sharedManager');
				if (plus.ios.invoke(manager, 'isAdvertisingTrackingEnabled')) {
					let identifier = plus.ios.invoke(manager, 'advertisingIdentifier');
					idfa = plus.ios.invoke(identifier, 'UUIDString');
					plus.ios.deleteObject(identifier);
				}
				plus.ios.deleteObject(manager);
			}
		} catch (e) {
			console.error('获取idfa失败');
		}
		return idfa;
	},
	/*
	 * obj 转 params字符串参数
	 * 例子：{a:1,b:2} => a=1&b=2
	 */
	objParseParam(obj) {
		let paramsStr = '';
		if (obj instanceof Array) return paramsStr;
		// if (!(obj instanceof Object)) return paramsStr;
		for (let key in obj) {
			paramsStr += `${key}=${obj[key]}&`;
		}
		return paramsStr
		return paramsStr.substring(0, paramsStr.length - 1);
	},
	/*
	 * obj 转 路由地址带参数
	 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
	 */
	objParseUrlAndParam(path, obj) {
		let url = path || '/';
		let paramsStr = '';
		if (obj instanceof Array) return url;
		// if (!(obj instanceof Object)) return url;
		paramsStr = this.objParseParam(obj);
		paramsStr && (url += '?');
		url += paramsStr;
		return url;
	},
	/*
	 * 获取url字符串参数
	 */
	getRequestParameters(locationhref) {
		let href = locationhref || '';
		let theRequest = new Object();
		let str = href.split('?')[1];
		if (str != undefined) {
			let strs = str.split('&');
			for (let i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
			}
		}
		return theRequest;
	},
	/**
	 * 加密字符串
	 */
	strEncode(str) {
		const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		let l = key.length;
		let a = key.split('');
		let s = '',
			b,
			b1,
			b2,
			b3;
		for (let i = 0; i < str.length; i++) {
			b = str.charCodeAt(i);
			b1 = b % l;
			b = (b - b1) / l;
			b2 = b % l;
			b = (b - b2) / l;
			b3 = b % l;
			s += a[b3] + a[b2] + a[b1];
		}
		return s;
	},
	/**
	 * 解密字符串
	 */
	// strDecode(str) {
	// 	const key = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	// 	let l = key.length;
	// 	let b,
	// 		b1,
	// 		b2,
	// 		b3,
	// 		d = 0,
	// 		s;
	// 	s = new Array(Math.floor(str.length / 3));
	// 	b = s.length;
	// 	for (let i = 0; i < b; i++) {
	// 		b1 = key.indexOf(str.charAt(d));
	// 		d++;
	// 		b2 = key.indexOf(str.charAt(d));
	// 		d++;
	// 		b3 = key.indexOf(str.charAt(d));
	// 		d++;
	// 		s[i] = b1 * l * l + b2 * l + b3;
	// 	}
	// 	b = eval('String.fromCharCode(' + s.join(',') + ')');
	// 	return b;
	// },
	/**
	 * 比较版本号
	 */
	compareVersion(reqV, curV) {
		if (curV && reqV) {
			let arr1 = curV.split('.'),
				arr2 = reqV.split('.');
			let minLength = Math.min(arr1.length, arr2.length),
				position = 0,
				diff = 0;
			while (
				position < minLength &&
				(diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0
			) {
				position++;
			}
			diff = diff != 0 ? diff : arr1.length - arr2.length;
			if (diff > 0) {
				if (position == minLength - 1) {
					return 1;
				} else {
					return 2;
				}
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	},
	/**
	 * H5复制
	 */
	h5Copy(content) {
		let textarea = document.createElement('textarea');
		textarea.value = content;
		textarea.readOnly = 'readOnly';
		document.body.appendChild(textarea);
		textarea.select(); // 选择对象
		textarea.setSelectionRange(0, content.length); //核心
		let result = document.execCommand('Copy'); // 执行浏览器复制命令
		textarea.remove();
		const msg = result ? '复制成功' : '复制失败';
		this.toast(msg);
	},
  // 去掉字符串中的空格
  trim(str){
    if (!str) {
        return '';
    }
    return str.replace(/\s*/g,'');
  },

  // 判断两个对象是否相同
  isObjectValueEqual(x, y) {
    // 指向同一内存时
    if (x === y) {
      return true;
    } else if (
      typeof x == 'object' &&
      x != null &&
      typeof y == 'object' && y != null
    ) {
      if (Object.keys(x).length != Object.keys(y).length) return false;

      for (var prop in x) {
        if (y.hasOwnProperty(prop)) {
          if (!this.isObjectValueEqual(x[prop], y[prop])) return false;
        } else return false;
      }

      return true;
    } else return false;
  },
	
	// 跳转到第三方app
	toOtherApp(url) {
		// #ifdef H5
		return window.open(url)
		// #endif
		// let url = 'https://detail.tmall.com/item.htm?id=616607750344';
		let openUrl = url;
		// 因为 url 一般是从其它地方获取的，所以这里要将 http 和 https 删去
		// 也可以直接输入 https:// 之后的内容，则不需要此步判断，直接调用 plus.runtime.openURL
		if (url.substr(0, 5) === 'https') {
			openUrl = `taobao://${url.substr(8)}`;
		} else if (url.substr(0, 4) === 'http') {
			openUrl = `taobao://${url.substr(7)}`;
		}
		plus.runtime.openURL(openUrl, function(res) {
			uni.showModal({
				content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
				success: function(res) {
					if (res.confirm) {
						plus.runtime.openURL(url);
					}
				}
			});
		})
	},
	
	// 根据角色动态获取tabbar
	getTabbar() {
		mTabbar()
		// return new Promise((resolve, reject) => {
		// 	const res = mTabbar(role)
		// 	resolve(res)
		// })
		// Vue.prototype.tabbar = tabbar
	},
	
	// 延时跳转
	delayedJump(url, type = 'back', time = 1000) {
		setTimeout(() => {
			if (type != 'back') {
				mRouter[type]({ route: url })
			} else {
				mRouter[type]()
			}
		}, time)
		
	},
	
	// 精确除法
	division(arg1, arg2) {
		let t1, t2, r1, r2;
		try{
			t1 = arg1.toString().split('.')[1].length;
		} catch(e) {
			t1 = 0;
		}
		try{
			t2 = arg2.toString().split('.')[1].length;
		} catch(e) {
			t2 = 0;
		}
		r1 = Number(arg1.toString().replace('.', ''));
		r2 = Number(arg2.toString().replace('.', ''));
		return (r1/r2) * Math.pow(10, t2 - t1);
	},
	
	// 时间格式化
	/**
	 * Parse the time to string
	 * @param {(Object|string|number)} time
	 * @param {string} cFormat
	 * @returns {string | null}
	 */
	parseTime(time, cFormat) {
	  if (arguments.length === 0 || !time) {
	    return null
	  }
	  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	  let date
	  if (typeof time === 'object') {
	    date = time
	  } else {
	    if ((typeof time === 'string')) {
	
	      if ((/^[0-9]+$/.test(time))) {
	        // support "1548221490638"
	        time = parseInt(time)
	      } else {
	        // support safari
	        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
	        if (time.includes('T')) {
	            time = time
	        } else {
	          time = time.replace(new RegExp(/-/gm), '/')
	        }
	      }
	    }
	
	    if ((typeof time === 'number') && (time.toString().length === 10)) {
	      time = time * 1000
	    }
	    date = new Date(time)
	  }
	  const formatObj = {
	    y: date.getFullYear(),
	    m: date.getMonth() + 1,
	    d: date.getDate(),
	    h: date.getHours(),
	    i: date.getMinutes(),
	    s: date.getSeconds(),
	    a: date.getDay()
	  }
	  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
	    const value = formatObj[key]
	    // Note: getDay() returns 0 on Sunday
	    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
	    return value.toString().padStart(2, '0')
	  })
	  return time_str
	},
	
	//浮点数解决计算封装
	getDecimalLength(num) { //获取小数位长度
	  let length=0;
	  try{
	      length =String(num).split('.')[1].length
	  }catch(e){
	      //TODO handle the exception
	  }
	  return length;
	},
	
	getBeishu(num1, num2) {  //获取放大倍数
	
	  let num1DecimalLength=this.getDecimalLength(num1);
	  let num2DecimalLength=this.getDecimalLength(num2);
	  let longer=Math.max(num1DecimalLength,num2DecimalLength);
	  return Math.pow(10,longer);
	},

	//加减乘除算法
	add(arg1, arg2) {
	  var r1, r2, m, c;
	  try {
	  r1 = arg1.toString().split(".")[1].length;
	  } catch (e) {
	  r1 = 0;
	  }
	  try {
	  r2 = arg2.toString().split(".")[1].length;
	  } catch (e) {
	  r2 = 0;
	  }
	  c = Math.abs(r1 - r2);
	  m = Math.pow(10, Math.max(r1, r2));
	  if (c > 0) {
	  var cm = Math.pow(10, c);
	  if (r1 > r2) {
	   arg1 = Number(arg1.toString().replace(".", ""));
	   arg2 = Number(arg2.toString().replace(".", "")) * cm;
	  } else {
	   arg1 = Number(arg1.toString().replace(".", "")) * cm;
	   arg2 = Number(arg2.toString().replace(".", ""));
	  }
	  } else {
	  arg1 = Number(arg1.toString().replace(".", ""));
	  arg2 = Number(arg2.toString().replace(".", ""));
	  }
	  return (arg1 + arg2) / m;
	 },
	 sub(num1, num2) {
	 
	  let beishu = this.getBeishu(num1, num2);
	  return (num1*beishu-num2*beishu)/beishu;
	},
	
	mul(num1,num2){
	  let num1DecLen=this.getDecimalLength(num1);
	  let num2DecLen=this.getDecimalLength(num2);
	  let num1toStr=String(num1);
	  let num2toStr=String(num2);
	  return Number(num1toStr.replace('.',''))*Number(num2toStr.replace('.',''))/Math.pow(10,num1DecLen+num2DecLen)
	},
	
	
	dev(num1,num2){
	  let num1DecLen=this.getDecimalLength(num1);
	  let num2DecLen=this.getDecimalLength(num2);
	  let num1toStr=String(num1);
	  let num2toStr=String(num2);
	  return Number(num1toStr.replace('.',''))/Number(num2toStr.replace('.',''))/Math.pow(10,num1DecLen-num2DecLen)
	},
	
	stringify(obj, sep, eq) {
	    sep = sep || '&';
	    eq = eq || '=';
	    let str = "";
	    for (var k in obj) {
			if(obj[k] instanceof Array){
				str+= this.initObj(k,obj[k]);
			}else{
				str += k + eq + unescape(obj[k]) + sep
			}
	    }
	    return str.slice(0, -1)
	},
	initObj(key,ary=[]){
		let str ='';
		let sep = '&';
		let eq =  '=';
		ary.forEach(item=>{
			let obj = new Object();
			str+= key + eq + item + sep
		})
		return str
	},
};
